package edu.maplef.bookwild.utils;

import com.google.gdata.client.douban.DoubanService;

import edu.maplef.bookwild.config.Config;
import edu.maplef.bookwild.config.Constants;

/**
 * 提供访问的数据服务
 * @author maple
 *
 */
public class DoubanServiceUtil {

	private static DoubanService[] db_pool;
	private static int idx = -1;
	private static int poolsize;
	private static String[] appnames;
	private static String[] apikeys;

	static {
		if (!Config.isInit)
			Config.init();
		appnames = Config.getConfig(Constants.DB_APPNAME).split(",");
		apikeys = Config.getConfig(Constants.DB_APIKEY).split(",");

		if (appnames.length != apikeys.length || appnames.length == 0) {
			try {
				throw new Exception("config file incorrect");
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(-1);
			}
		}
		poolsize = appnames.length;
		db_pool = new DoubanService[poolsize];
	}

	private DoubanServiceUtil() {

	}

	public synchronized static DoubanService getDoubanService() {
		try {
			idx++;
			idx %= poolsize;
			if (db_pool[idx] == null) {
				db_pool[idx] = new DoubanService(appnames[idx], apikeys[idx]);
			}
			return db_pool[idx];
		} catch (Exception e) {
			e.printStackTrace();
			return getDoubanService();
		}
	}
}
